'--------------------------------------------------------------
'                     (c) 1999-2002 MCS Electronics
'--------------------------------------------------------------
'  file: I2C.BAS
'  demo: I2CSEND and I2CRECEIVE
'--------------------------------------------------------------
$baud = 9600
$crystal = 8000000
Config Scl = Portc.0
Config Sda = Portc.1
Declare Sub Write_eeprom(byval Adres As Byte , Byval Value As Byte)
Declare Sub Read_eeprom(byval Adres As Byte , Value As Byte)

Const Addressw = 160                                        'slave write address
Const Addressr = 161                                        'slave read address

Dim B1 As Byte , Adres As Byte , Value As Byte              'dim byte
Dim H As Byte , L As Byte , I As Integer
Call Write_eeprom(0 , 0)                                    'write value of three to address 1 of EEPROM
I = 1
While I > 0

'Call Read_eeprom(1 , Value) : Print " 1 is " ; Value        'read it back
Call Read_eeprom(2 , Value) : Print " 2 is " ; Value        'read it back
Call Read_eeprom(3 , Value) : Print " 3 is " ; Value        'read it back
Call Read_eeprom(4 , Value) : Print " 4 is " ; Value        'read it back
'Call Read_eeprom(5 , Value) : Print " 5 is " ; Value        'read it back
'Call Read_eeprom(6 , Value) : Print " 6 is " ; Value        'read it back
'Call Read_eeprom(7 , Value) : Print " 7 is " ; Value        'read it back
Wait 1
Wend
End


Rem Note That The Slaveaddress Is Adjusted Automaticly With I2csend & I2creceive
Rem This Means You Can Specify The Baseaddress Of The Chip.


'sample of writing a byte to EEPROM AT2404
Sub Write_eeprom(byval Adres As Byte , Byval Value As Byte)
    I2cstart                                                'start condition
    I2cwbyte Addressw                                       'slave address
    I2cwbyte Adres                                          'asdress of EEPROM
    I2cwbyte Value                                          'value to write
    I2cstop                                                 'stop condition
    Waitms 10                                               'wait for 10 milliseconds
End Sub

Sub Read_eeprom(byval Adres As Byte , Value As Byte)
   I2cstart                                                 'generate start
   I2cwbyte Addressw                                        'slave adsress
   I2cwbyte Adres                                           'address of EEPROM
   I2cstart                                                 'repeated start
   I2cwbyte Addressr                                        'slave address (read)
   I2crbyte Value , Nack                                    'read byte
   I2cstop                                                  'generate stop
End Sub